/**
 * Created by zhaolei on 2017/4/26.
 */
package com.zl.learning.io.test.com.ronsoft.books.nio.channels;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 * Test channel transfer. This is a very simplistic concatenation
 * program. It takes a list of file names as arguments, opens each
 * in turn and transfers (copies) their content to the given
 * WritableByteChannel (in this case, stdout).
 * <p>
 * 96
 * Created April 2002
 *
 * @author Ron Hitchens (ron@ronsoft.com)
 */
public class ChannelTransfer {
    public static void main(String[] argv)
            throws Exception {
//        if (argv.length == 0) {
//            System.err.println ("Usage: filename ...");
//            return;
//        }
        tailFiles(Channels.newChannel(System.out), new String[]{"C:\\workspace\\3.txt"});
    }

    // Concatenate the content of each of the named files to
// the given channel. A very dumb version of 'cat'.
    private static void catFiles(WritableByteChannel target,
                                 String[] files)
            throws Exception {
        for (int i = 0; i < files.length; i++) {
            FileInputStream fis = new FileInputStream(files[i]);
            FileChannel channel = fis.getChannel();
            channel.transferTo(0, channel.size(), target);
            channel.close();
            fis.close();
        }
    }

    private static void tailFiles(WritableByteChannel target, String[] files) throws IOException, InterruptedException {
        ServerSocket serverSocket = new ServerSocket(88);
        final Socket socket = serverSocket.accept();
        final OutputStream outputStream = socket.getOutputStream();
        String file = files[0];
        FileInputStream fis = new FileInputStream(file);
        FileChannel channel = fis.getChannel();
        long position = 0;
        final WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);
        while (true) {
            channel.transferTo(position, channel.size(), writableByteChannel);
            position = channel.size();
            Thread.sleep(500);
        }
    }
}